package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //处理超时订单方法(每分钟执行一次)
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrder() {
        log.info("定时处理超时订单");
        // 获取所有超时的订单
        //select * from orders where status = ? and order_time<(当前时间-15分钟)
        List<Orders> list = orderMapper.getBystatusAndTime(1, LocalDateTime.now().minusMinutes(15));
        //如果存在超时订单，就修改订单状态为已取消
        // 请注意，不能把返回的订单ID存入数据库，因为是外键
        if (!CollectionUtils.isEmpty(list)) {
            for (Orders order : list) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }

    }
    /*
     *处理一直都是派送中的单子，每天凌晨一点处理
     * */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder() {
        log.info("定时处理派送中订单");
        // 获取所有派送中的订单
        List<Orders> list = orderMapper.getBystatusAndTime(4, LocalDateTime.now().minusHours(1));
        // 如果存在派送中的订单，就修改订单状态为已发货
        if (!CollectionUtils.isEmpty(list)) {
            for (Orders order: list) {
                order.setStatus(Orders.COMPLETED);
                order.setCancelReason("订单派送成功");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }

    }




}
